import React, { Component } from 'react';
import {Text, View, Image, TextInput, TouchableOpacity, DeviceEventEmitter} from 'react-native';
import { base } from "../../assets/style";
import LinearGradient from "react-native-linear-gradient";
import Toast from 'react-native-easy-toast'
import Loading from '../../components/loading/index'
const md5 = require('md5')
import { API } from "../../api";
import {login} from "../../utils/login";
import { DeviceStorage } from "../../utils/DeviceStorage";
import { setStateAsync } from "../../utils/utils";
import I18n from "react-native-i18n";
import { i18n } from "../../utils/locales/i18n";

type Props = {};
export default class LoginScreen extends Component<Props> {
	static navigationOptions = {
		header: null,
		headerStyle: {
		},
		headerTintColor: '#0f0f0f',
		headerBackTitle: null
	};
	constructor() {
		super()
		this.state = {
			account: '',
			password: '',
			modalVisible: false,
			currentToastInfo: ''
		}
	}
	// 分发登录方式
	dispatchLogin = () => {
		if (this.state.account === '') {
			this.refs.toast.show(i18n.t('i226'))
			return
		}
		if (this.state.password === '') {
			this.refs.toast.show(i18n.t('i227'))
			return
		}
		if (this.state.account.indexOf('@') === -1) {
			// 手机登录
			this.sendPhoneLogin()
		} else {
			this.sendEmailLogin()
		}
	}
	// 手机登录
	sendPhoneLogin = async () => {
		this.setState({ modalVisible: true, currentToastInfo: i18n.t('i228') })
		const res = await API.phoneLogin({
			phone: this.state.account,
			password: md5(md5(this.state.password))
		})
		this.setState({ modalVisible: false, currentToastInfo: '' })
		// code: 10000
		// data: {IsOpenGoogle: 0, Uuid: "3f0c0e7e-02d8-6dec-69f2-991de497f789"}
		// 0 不需要 1 需要
		// msg: "登录成功"
		// status: 200
		if (res.code === 10000) {
			// 登陆成功
			if (res.data.IsOpenGoogle === 0) {
				// 不需要谷歌两步验证
				await login(res.data.Uuid)
				// this.setState({ modalVisible: false, currentToastInfo: '' })
				this.refs.toast.show(res.msg || i18n.t('i229'))
				setTimeout(() => {
					this.props.navigation.navigate('AppScreen')
				}, 0)
			} else if (res.data.IsOpenGoogle === 1) {
				// 需要两步验证
				setTimeout(() => {
					this.props.navigation.navigate('GoogleVerify', { uuid: res.data.Uuid })
				}, 0)
			} else {
				// 出错
				this.refs.toast.show('error: unrecognized google verify status code: ' + res.data.IsOpenGoogle)
				return
			}
		} else {
			// 登录失败
			this.refs.toast.show(res.msg)
		}
	}
	// 邮箱登录
	sendEmailLogin = async () => {
		this.setState({ modalVisible: true, currentToastInfo: i18n.t('i228') })
		const res = await API.emailLogin({
			email: this.state.account.trim(),
			password: md5(md5(this.state.password))
		})
		this.setState({ modalVisible: false, currentToastInfo: '' })
		// code: 10000
		// data: {IsOpenGoogle: 0, Uuid: "3f0c0e7e-02d8-6dec-69f2-991de497f789"}
		// 0 不需要 1 需要
		// msg: "登录成功"
		// status: 200
		if (res.code === 10000) {
			// 登陆成功
			if (res.data.IsOpenGoogle === 0) {
				// 不需要谷歌两步验证
				await login(res.data.Uuid)
				this.refs.toast.show(res.msg || i18n.t('i229'))
				setTimeout(() => {
					this.props.navigation.navigate('AppScreen')
				}, 0)
			} else if (res.data.IsOpenGoogle === 1) {
				// 需要两步验证
				setTimeout(() => {
					this.props.navigation.navigate('GoogleVerify', { uuid: res.data.Uuid })
				}, 0)
			} else {
				// 出错
				this.refs.toast.show('error: unrecognized google verify status code: ' + res.data.IsOpenGoogle)
				return
			}
		} else {
			// 登录失败
			this.refs.toast.show(res.msg)
		}
	}
	componentDidMount(): void {
		this._getUserInfo()
		DeviceStorage.get('lang').then(lang => {
			if (lang) {
				i18n.locale = lang || 'tw'
				console.log('lang: ', lang);
			} else {
				DeviceStorage.set('lang', 'tw')
				i18n.locale = 'tw'
			}
		}).catch(e => {
			console.log(e);
		})
	}
	// 获取用户信息
	_getUserInfo = async () => {
		this.setState({
			modalVisible: true
		})
		const jwt = await DeviceStorage.get('jwt')
		if (jwt) {
			const res = await API.getUserInfo()
			if (res && res.code && res.code === 10000) {
				await DeviceStorage.set('user_info', JSON.stringify(res.data))
				this.setState({
					modalVisible: false
				})
				setTimeout(() => {
					this.props.navigation.navigate('AppScreen')
				}, 0)
				return
			} else {
				this.setState({
					modalVisible: false
				})
				return
			}
		}
		this.setState({
			modalVisible: false
		})
	}

	render() {
		return (
			<View style={[base.bg_white, base.flex_1]}>
				{/*toast*/}
				<Toast ref="toast" position='bottom'/>
				{ this.state.modalVisible ? (
					<Loading
						info={this.state.currentToastInfo}
					/>) : null }
				<View style={[base.flex_row_center, { height: '40%', position: 'relative' }]}>
					{/*跳过登录*/}
					<View style={[base.flex_row_end, { width: '100%', paddingRight: 20, position: 'absolute', top: '10%', left: 0 }]}>
						<TouchableOpacity
							style={[base.flex_row_center]}
							onPress={() => this.props.navigation.navigate('AppScreen')}
						>
							<Text style={[base.color_gray, { fontSize: 18 }]}>{i18n.t('i230')}</Text>
						</TouchableOpacity>
					</View>
					<Image style={{width: 120, height: 120}} resizeMode={'contain'} source={require('@images/login/login_logo.png')}/>
				</View>
				<View style={[base.flex_1, {paddingHorizontal: 40}]}>
					<View>
						<View style={[base.flex_row_between, { borderBottomColor: '#b2b2b2', height: 50, borderBottomWidth: 0.3, marginTop: 10, paddingBottom: 2 }]}>
							<View style={[base.flex_row_center, { width: 100 }]}>
								<Text style={{fontSize: 18}}>{i18n.t('i231')}</Text>
							</View>
							<View style={[base.flex_1, base.flex_row_start]}>
								<TextInput
									placeholder={i18n.t('i226')}
									style={[base.color_gray]}
									value={this.state.account}
									autoCapitalize={'none'}
									onChangeText={(text) => this.setState({account: text})}
								/>
							</View>
						</View>
						<View style={[base.flex_row_between, { borderBottomColor: '#b2b2b2', height: 50, borderBottomWidth: 0.3, marginTop: 20, paddingBottom: 2 }]}>
							<View style={[base.flex_row_center, { width: 100 }]}>
								<Text style={{fontSize: 18}}>{i18n.t('i232')}</Text>
							</View>
							<View style={[base.flex_1]}>
								<TextInput
									placeholder={i18n.t('i227')}
									style={[base.color_gray]}
									value={this.state.password}
									secureTextEntry={true}
									onChangeText={(text) => this.setState({password: text})}
								/>
							</View>
						</View>
						<View style={[base.flex_row_end, { marginVertical:  20}]}>
							<TouchableOpacity onPress={() => this.props.navigation.navigate('Forgot')} style={{ borderBottomColor: '#808080', borderBottomWidth: 0.5 }}>
								<Text style={{ color: '#808080' }}>{i18n.t('i233')}</Text>
							</TouchableOpacity>
						</View>
					</View>
					<View style={[base.flex_1, base.flex_col_start, {paddingTop: 0, width: '100%'}]}>
						<View style={[base.flex_col_center, { width: '100%', marginTop: 20 }]}>
							<TouchableOpacity onPress={this.dispatchLogin} style={{width: '100%'}}>
								<LinearGradient
									start={{x: 0, y: 0}}
									end={{x: 1, y: 1}}
									colors={['#feac1c', '#ff7506']}
									style={{ width: '100%', height: 46, borderRadius: 23, justifyContent: 'center', alignItems: 'center' }}
								>
									<Text style={{color: '#fff', fontSize: 16}}>{i18n.t('i235')}</Text>
								</LinearGradient>
							</TouchableOpacity>
						</View>
						<View style={[base.flex_col_center, { width: '100%', marginTop: '10%' }]}>
							<TouchableOpacity onPress={() => this.props.navigation.navigate('Register')} style={{width: '100%'}}>
								<View
									style={{ width: '100%', height: 46, borderRadius: 23, borderColor: '#a8a8a8', borderWidth: 0.3, justifyContent: 'center', alignItems: 'center' }}
								>
									<Text style={{color: '#808080', fontSize: 16}}>{i18n.t('i234')}</Text>
								</View>
							</TouchableOpacity>
						</View>
					</View>
				</View>
			</View>
		);
	}
}
